package com.xiaoyu.studyworkspace.controller;

import com.xiaoyu.studyworkspace.common.util.JwtUtil;
import com.xiaoyu.studyworkspace.common.util.Result;
import com.xiaoyu.studyworkspace.dto.UserDTO;
import com.xiaoyu.studyworkspace.pojo.User;
import com.xiaoyu.studyworkspace.properties.JwtProperties;
import com.xiaoyu.studyworkspace.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin("*")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) throws IOException {
        //卡帕id
        String relationInfo = userDTO.getRelation_info();
        //判断缓存当中是否存在该id
        boolean haveRedis = userService.haveRedis(relationInfo);
        if (haveRedis) {
            //存在返回
            Result<String> error = Result.error("当前ID正在使用！");
            return error;
        }
        //缓存和数据查询
        User user = userService.findUser(relationInfo);
        if (user != null) {
            String token = JwtUtil.createToken(user.getRelation_info(), jwtProperties.getSecretKey(), jwtProperties.getLongTime());
            //存入redis中
            redisTemplate.opsForValue().set(relationInfo, token);
            //设置5秒过期
            redisTemplate.expire(relationInfo, 5, TimeUnit.SECONDS);
            Result<String> success = Result.success(token, "成功！");
            return success;
        }
        //缓存和数据库都不存在，判断是否转账
        String userId = userService.checkUser(relationInfo);
        if (!"".equals(userId)) {
            String token = JwtUtil.createToken(userId, jwtProperties.getSecretKey(), jwtProperties.getLongTime());
            Result<String> success = Result.success(token, "成功！");
            //存入redis中
            redisTemplate.opsForValue().set(relationInfo, token);
            //设置5秒过期
            redisTemplate.expire(relationInfo, 5, TimeUnit.SECONDS);
            return success;
        }

        Result<String> error = Result.error("ID过期未转账");
        return error;
    }


    @GetMapping("/check")
    public Result checkToken(@RequestParam String token) {
        Boolean checkToken = JwtUtil.checkToken(token);
        if (checkToken) {
            //正常
            Result<String> success = Result.success(null, "校验成功！");
            return success;
        }
        Result<String> error = Result.error("校验成功！");
        return error;
    }

}
